package com.mlk.repair.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.collect.Lists;
import com.mlk.busPram.constant.BusParamConstant;
import com.mlk.busPram.mapper.EngBusParamMapper;
import com.mlk.busPram.po.EngBusParam;
import com.mlk.constant.EngConstant;
import com.mlk.core.component.page.Page;
import com.mlk.core.component.page.Pager;
import com.mlk.core.exception.GlobalException;
import com.mlk.core.util.FileUploadUtils;
import com.mlk.core.util.ServerResponse;
import com.mlk.core.util.UUIDUtils;
import com.mlk.core.util.validate.ValidateUtils;
import com.mlk.repair.mapper.EngRepairTicketItemMapper;
import com.mlk.repair.mapper.EngRepairTicketMapper;
import com.mlk.repair.mapper.EngRepairTicketPicMapper;
import com.mlk.repair.po.EngRepairTicket;
import com.mlk.repair.po.EngRepairTicketItem;
import com.mlk.repair.po.EngRepairTicketPic;
import com.mlk.repair.service.EngRepairService;
import com.mlk.repair.vo.EngRepairTicketItemVO;
import com.mlk.repair.vo.EngRepairTicketVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 报备服务
 */
@Service
public class EngRepairServiceImpl implements EngRepairService {


    @Resource
    private EngRepairTicketMapper engRepairTicketMapper;

    @Resource
    private EngRepairTicketPicMapper engRepairTicketPicMapper;

    @Resource
    private EngRepairTicketItemMapper engRepairTicketItemMapper;

    @Resource
    private EngBusParamMapper engBusParamMapper;

    /**
     * 上传报备文件的处理内容
     *
     * @param pic
     * @param file
     * @return
     */
    @Override
    @Transactional
    public ServerResponse addPic(EngRepairTicketPic pic, MultipartFile file) {
        FileUploadUtils.UploadContext context = null;
        if ((context = FileUploadUtils.uploadContext(file, EngConstant.PicPath.REPAIR_PATH, UUIDUtils.uuid())).getSuccess()) {
            pic.setPicUrl(context.getSaveFullPath());
            int count = this.engRepairTicketPicMapper.insert(pic);
            return count == 0 ? ServerResponse.fail("添加失败") : ServerResponse.ok(pic);
        }

        throw new GlobalException("添加失败");
    }

    /**
     * 删除报备图片
     *
     * @param id
     * @return
     */
    @Override
    @Transactional
    public ServerResponse delPic(Integer id) {
        int count = this.engRepairTicketPicMapper.deleteById(id);
        if (count == 0) {
            throw new GlobalException("删除图片失败");
        }

        return ServerResponse.ok("删除图片成功");
    }

    /**
     * 报备单新增
     *
     * @param vo
     * @return
     */
    @Override
    @Transactional
    public ServerResponse addTicket(EngRepairTicketVO vo) {
        // 校验主体信息
        ValidateUtils.validate(vo);
        // 生成一个ticket
        String ticketId = IdUtil.createSnowflake(4L, 4L).nextIdStr();

        // 添加报备单主题信息
        EngRepairTicket ticket = new EngRepairTicket();
        BeanUtils.copyProperties(vo, ticket);
        ticket.setTicketId(ticketId);
        ticket.setCreateTime(new Date());
        int count = this.engRepairTicketMapper.insert(ticket);
        if (count == 0) {
            throw new GlobalException("报备失败");
        }

        // 下面添加明细信息
        if (CollectionUtils.isEmpty(vo.getItems())) {
            return ServerResponse.ok("报备成功");
        }

        // 添加报备信息
        vo.getItems().stream().forEach(element -> {
            ValidateUtils.validate(element);
            EngRepairTicketItem item = new EngRepairTicketItem();
            BeanUtils.copyProperties(element, item);
            item.setTicketId(ticketId);
            // 添加明细信息
            this.engRepairTicketItemMapper.insert(item);
        });


        return ServerResponse.ok("备案成功");
    }

    /**
     * 查询我的报备单
     *
     * @param openId
     * @return
     */
    @Override
    @Page
    public Pager queryMyRepair(String openId) {
        EngRepairTicketVO ticket = new EngRepairTicketVO();
        ticket.setOpenId(openId);
        List<EngRepairTicketVO> lists = this.engRepairTicketMapper.selectForPage(ticket);

        // 进行状态的格式化
        lists.stream().forEach(element -> {
            String statusName = EngConstant.REPAIR_STATUS_REF.adapt(element.getStatus());
            element.setStatusName(statusName);
        });

        return Pager.adapt(lists);
    }

    /**
     * 查询报备单详情
     *
     * @param ticketId
     * @return
     */
    @Override
    public ServerResponse queryRepairTickInfo(String ticketId) {
        List<EngRepairTicketItem> items = this.engRepairTicketItemMapper.selectList(new EntityWrapper<>(EngRepairTicketItem.builder().ticketId(ticketId).build()));

        List<EngRepairTicketItemVO> result = Lists.newArrayList();

        items.stream().forEach(element -> {
            List<EngRepairTicketPic> pics = this.engRepairTicketPicMapper.selectList(new EntityWrapper<>(EngRepairTicketPic.builder().uniCode(element.getUniCode()).build()));
            EngRepairTicketItemVO temp = new EngRepairTicketItemVO();
            BeanUtils.copyProperties(element, temp);
            temp.setPics(pics);
            result.add(temp);
        });

        return ServerResponse.ok(result);
    }

    /**
     * 分页展示数据
     *
     * @param vo
     * @return
     */
    @Override
    @Page
    public Pager listPage(EngRepairTicketVO vo) {
        return Pager.adapt(this.engRepairTicketMapper.selectForPage(vo));
    }

    /**
     * 接收报备单
     *
     * @param ticket
     * @return
     */
    @Override
    public ServerResponse accept(EngRepairTicket ticket) {
        ticket.setStatus(EngConstant.REPAIR_STATUS.ACCEPT_STATUS);
        ticket.setHandleTime(new Date());
        int count = this.engRepairTicketMapper.updateById(ticket);
        if (count == 0) {
            throw new GlobalException("接收报备单失败");
        }
        return ServerResponse.ok("接收报备单成功");
    }

    /**
     * 完成报备
     *
     * @param ticket
     * @return
     */
    @Override
    @Transactional
    public ServerResponse finish(EngRepairTicket ticket) {
        if (this.checkTicketCanComplete(ticket.getTicketId()).isSuccess()) {
            // 现在说明可以结束报备单..

            ticket.setStatus(EngConstant.REPAIR_STATUS.FINISH_STATUS);
            int count = this.engRepairTicketMapper.updateById(ticket);
            if (count == 0) {
                throw new GlobalException("接收报备单失败");
            }
            return ServerResponse.ok("接收报备单成功");
        }

        throw new GlobalException("报备失败");
    }

    /**
     * 校正参数
     *
     * @param ticket
     * @return
     */
    @Override
    public ServerResponse just(EngRepairTicketItem ticket) {
        int count = this.engRepairTicketItemMapper.updateById(ticket);
        if (count == 0) {
            throw new GlobalException("校正失败");
        }
        return ServerResponse.ok("校正成功");
    }

    /**
     * 校验是否能完成报备工作
     *
     * @param ticketId
     * @return
     */
    @Override
    public ServerResponse checkTicketCanComplete(String ticketId) {
        // 进行一下校验
        List<EngRepairTicketItem> items = this.engRepairTicketItemMapper.selectList(new EntityWrapper<>(EngRepairTicketItem.builder().ticketId(ticketId).build()));
        items.forEach(element -> {
            // 判断内容是否都已经补充到业务数据之中.
            int count = this.engBusParamMapper.selectCount(new EntityWrapper<>(EngBusParam.builder().type(BusParamConstant.BRANCH_TYPE).name(element.getBranch()).build()));
            if (count == 0) {
                throw new GlobalException("品牌" + element.getBranch() + "不在售后维护参数之中,请选择修改或者添加到售后维护数据之中");
            }
            count = this.engBusParamMapper.selectCount(new EntityWrapper<>(EngBusParam.builder().type(BusParamConstant.PARAM_TYPE).name(element.getParam()).build()));
            if (count == 0) {
                throw new GlobalException("型号" + element.getBranch() + "不在售后维护参数之中,请选择修改或者添加到售后维护数据之中");
            }
            count = this.engBusParamMapper.selectCount(new EntityWrapper<>(EngBusParam.builder().type(BusParamConstant.FAULT_TYPE).name(element.getRemark()).build()));
            if (count == 0) {
                throw new GlobalException("故障类型" + element.getBranch() + "不在售后维护参数之中,请选择修改或者添加到售后维护数据之中");
            }
        });

        return ServerResponse.ok();
    }

    /**
     * 查询一个报备的详情
     *
     * @param id
     * @return
     */
    @Override
    public EngRepairTicketVO findAllInfoOfRepair(Integer id) {
        EngRepairTicket ticket = this.engRepairTicketMapper.selectById(id);
        // 处理主体信息
        EngRepairTicketVO vo = new EngRepairTicketVO();
        BeanUtils.copyProperties(ticket, vo);
        // 转换单位
        vo.setStatusName(EngConstant.REPAIR_STATUS_REF.adapt(vo.getStatus()));

        // 查询items
        List<EngRepairTicketItem> items = this.engRepairTicketItemMapper.selectList(new EntityWrapper<>(EngRepairTicketItem.builder().ticketId(vo.getTicketId()).build()));

        List<EngRepairTicketItemVO> itemsVO = Lists.newArrayList();

        items.forEach(element -> {
            EngRepairTicketItemVO item = new EngRepairTicketItemVO();
            BeanUtils.copyProperties(element, item);
            // 查询图片信息
            List<EngRepairTicketPic> pics = this.engRepairTicketPicMapper.selectList(new EntityWrapper<>(EngRepairTicketPic.builder().uniCode(item.getUniCode()).build()));
            item.setPics(pics);
            itemsVO.add(item);
        });

        vo.setItems(itemsVO);

        return vo;
    }

    /**
     * 智能输入
     *
     * @param ticket
     * @return
     */
    @Override
    public ServerResponse AIInput(EngRepairTicket ticket) {
        return ServerResponse.ok(this.engRepairTicketMapper.AIInput(ticket));
    }
}
